package com.rybbaby.tss.${baseInfo.modulesName}.${baseInfo.entityName?uncapFirst}.controller;

import java.io.IOException;
import java.io.Serializable;
<#list table.columns as column>
<#if column.datasourceSql??&&column.datasourceSql!="">
import java.util.List;
<#break>
</#if>
</#list>
import java.util.Map;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.AjaxJsonResponse;
import com.rybbaby.tss.core.utils.PropertiesReadUtil;
import com.rybbaby.tss.core.utils.SequenceUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.${baseInfo.modulesName}.${baseInfo.entityName?uncapFirst}.entity.${baseInfo.entityName};
import com.rybbaby.tss.${baseInfo.modulesName}.${baseInfo.entityName?uncapFirst}.service.I${baseInfo.entityName}Service;

/**
 * @description ${baseInfo.businessDescription}管理
 * 
 * @author ${baseInfo.author}
 * 
 * @createDate ${baseInfo.nowDate}
 */
@Controller
@RequestMapping(value = "${baseInfo.entityName?uncapFirst}Controller")
public class ${baseInfo.entityName}Controller extends BaseController {
	
	@Autowired
	private I${baseInfo.entityName}Service ${baseInfo.entityName?uncapFirst}Service;
	
	/**
	 * 获取${baseInfo.businessDescription}列表
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestLog(content = "获取${baseInfo.businessDescription}列表" , save = true)
	@Token(createToken = true , validateToken = true)
	@RequestMapping(value = "${baseInfo.entityName?uncapFirst}List" , method = RequestMethod.POST)
	public ModelAndView ${baseInfo.entityName?uncapFirst}List(${baseInfo.entityName} entity , PageBean paramPageBean) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("${baseInfo.entityName?uncapFirst}ListView"));
		try {
			Map<String , String []> unLockMap = getParameterMap(request);
			DetachedCriteria dc = DetachedCriteria.forClass(${baseInfo.entityName}.class);
			HqlGenerateUtil.fillDetachedCriteria(dc , entity , unLockMap);
			PageBean pageBean = ${baseInfo.entityName?uncapFirst}Service.pageList(dc , paramPageBean.getPageNo() , paramPageBean.getPageSize());
			mav.addObject(super.SEARCH_MAP , unLockMap);
			mav.addObject(super.PAGE_BEAN , pageBean);
			mav.addObject("searchFormId" , SEARCH_FORM);
			mav.addObject("actionUrl" , request.getRequestURI());
			mav.addObject("pagingBar" , pageBean.getPagingBar(SEARCH_FORM));
			mav.addObject("serializeNum" , SequenceUtil.getUpperCaseUUID());
			String requestURI = StringUtils.substringBeforeLast(request.getRequestURI() , "/");
			mav.addObject("editUrl" , requestURI + "/toEditView.do");
			mav.addObject("deleteUrl" , requestURI + "/delete.do");
			mav.addObject("batchDeleteUrl" , requestURI + "/batchDelete.do");
		} catch (Exception e) {
			throw e;
		}
		return mav;
	}
	
	/**
	 * 转到编辑视图
	 * 
	 * @param entity
	 *            接收编辑参数的临时对象
	 * @param serializeNum
	 *            请求标识
	 * @return
	 */
	@RequestLog(content = "转到${baseInfo.businessDescription}视图" , save = true)
	@Token(createToken = true , validateToken = true)
	@RequestMapping(value = "toEditView" , method = RequestMethod.GET)
	public ModelAndView toEditView(${baseInfo.entityName} entity , @RequestParam(required = true) String serializeNum) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("${baseInfo.entityName?uncapFirst}EditView"));
		if(entity != null && <#list table.columns as column><#-- 主键--><#if column.isPrimaryKey>entity.get${column.columnJavaGetterOrSetterSuffix}()</#if></#list> != null) {
			${baseInfo.entityName} editEntity = this.${baseInfo.entityName?uncapFirst}Service.get(<#list table.columns as column><#-- 主键--><#if column.isPrimaryKey>entity.get${column.columnJavaGetterOrSetterSuffix}()</#if></#list>);
			mav.addObject("editEntity" , editEntity);
			mav.addObject("editModel" , "edit");
		}else{
			mav.addObject("editModel" , "add");
		}
		<#list table.columns as column>
		<#if column.datasourceSql??&&column.datasourceSql!="">
		// ${column.datasourceName}数据源
		List<Map<String , Object>> ${column.columnJavaFieldName}_datasources = this.${baseInfo.entityName?uncapFirst}Service.${column.columnJavaFieldName?uncapFirst}Datasource();
		mav.addObject("${column.columnJavaFieldName}_datasources" , ${column.columnJavaFieldName}_datasources);
		</#if>
		</#list>
		mav.addObject("serializeNum" , serializeNum);
		mav.addObject("saveUrl" , StringUtils.substringBeforeLast(request.getRequestURI() , "/") + "/saveOrUpdate.do");
		return mav;
	}
	
	/**
	 * 保存编辑的对象
	 * 
	 * @param entity
	 *            被编辑对象
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "保存${baseInfo.businessDescription}对象" , save = true)
	@Token(createToken = true , validateToken = true)
	@RequestMapping(value = "saveOrUpdate" , method = RequestMethod.POST)
	public String saveOrUpdate(${baseInfo.entityName} entity) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			<#assign uploadFileFields=""/>
			<#assign isstatement="0"/>
			<#list table.columns as column>
			<#-- 主键-->
			<#if column.isPrimaryKey>
			${column.columnJavaType} id=entity.get${column.columnJavaGetterOrSetterSuffix}();
			</#if>
			<#--上传文件-->
			<#if column.ucf??>
			<#if isstatement=="0">
			StringBuffer delteFileIds=new StringBuffer();
			<#assign isstatement="1"/>
			</#if>
			<#assign uploadFileFields="${uploadFileFields},${column.ucf.groupName}"/>
			// 新上传的文件映射:格式：groupName=>${column.columnJavaFieldName}
			String ${column.ucf.groupName} = getParameter("new${column.columnJavaGetterOrSetterSuffix}");
			// 字段${column.columnJavaFieldName}被删除历史文件id,格式：id1,id2,id3...idn
			String delete${column.columnJavaGetterOrSetterSuffix} = getParameter("delete${column.columnJavaGetterOrSetterSuffix}");
			delteFileIds.append(delete${column.columnJavaGetterOrSetterSuffix});
			</#if>
			</#list>
			ajr.setResMsg("保存成功!");
			<#if (column.columnJavaType)!"" == "java.lang.Integer"||(column.columnJavaType)!"" == "int">
			if(id!=null) {
			<#else>
			if(StringUtils.isNotBlank(id)){
			</#if>
				${baseInfo.entityName} destEntity = this.${baseInfo.entityName?uncapFirst}Service.get(id);
				<#assign timeFields=" "/>
				<#list table.columns as column>
					<#-- 时间类型-->
					<#if column.columnJavaType=="java.sql.Timestamp"||column.columnJavaType=="java.util.Date">
						<#assign timeFields="${timeFields},\"${column.columnJavaFieldName}\""/>
					</#if>
				</#list>
				BeanUtils.copyProperties(entity , destEntity${timeFields});
				<#list table.columns as column>
				<#-- 为修改时间 -->
				<#if column.isModifiedTime???string(column.isModifiedTime?string("yes","no"),"no")=="yes">
				<#-- 时间类型-->
				<#switch column.columnJavaType>
				<#case "java.sql.Timestamp">
				destEntity.set${column.columnJavaGetterOrSetterSuffix}(new java.sql.Timestamp(System.currentTimeMillis()));
				<#break>
				<#case "java.util.Date">
				destEntity.set${column.columnJavaGetterOrSetterSuffix}(new java.util.Date());
				<#break>
				</#switch>
				</#if>
				</#list>
				<#--上传文件-->
				<#if uploadFileFields??&&uploadFileFields!="">
				this.${baseInfo.entityName?uncapFirst}Service.updateEntitiy(destEntity, getSession().getId() , getLoginUserId() + "" , delteFileIds.toString() ${uploadFileFields});
				<#else>
				this.${baseInfo.entityName?uncapFirst}Service.updateEntitiy(destEntity);
				</#if>
			} else {
				<#list table.columns as column>
				<#-- 创建人 -->
				<#if column.isNowLoginUserIdentifying???string(column.isNowLoginUserIdentifying?string("yes","no"),"no")=="yes">
				Object loginUserId_obj=getLoginUserId();
				<#if column.columnJavaType=="java.lang.Integer">
				entity.set${column.columnJavaGetterOrSetterSuffix}(loginUserId_obj == null ? null : Integer.parseInt(loginUserId_obj.toString()));
				<#else>
				entity.set${column.columnJavaGetterOrSetterSuffix}(loginUserId_obj == null ? null : loginUserId_obj.toString());
				</#if>
				</#if>
				<#-- 为创建时间 -->
				<#if column.isCreateTime???string(column.isCreateTime?string("yes","no"),"no")=="yes">
				<#-- 时间类型-->
				<#switch column.columnJavaType>
				<#case "java.sql.Timestamp">
				entity.set${column.columnJavaGetterOrSetterSuffix}(new java.sql.Timestamp(System.currentTimeMillis()));
				<#break>
				<#case "java.util.Date">
				entity.set${column.columnJavaGetterOrSetterSuffix}(new java.util.Date()));
				<#break>
				</#switch>
				</#if>
				</#list>
				<#if uploadFileFields??&&uploadFileFields!="">
				Serializable newId =this.${baseInfo.entityName?uncapFirst}Service.save(entity, getSession().getId() , getLoginUserId() + "" ${uploadFileFields});
				<#else>
				Serializable newId = this.${baseInfo.entityName?uncapFirst}Service.save(entity);
				</#if>
				if(newId == null) {
					ajr.setResCode(301);
					ajr.setResMsg("保存失败!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}
	
	/**
	 * 删除指定id的对象
	 * 
	 * @param id
	 *            需要被删除的对象id
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "删除属性" , save = true)
	@Token(createToken = true , validateToken = true)
	@RequestMapping(value = "delete" , method = RequestMethod.GET)
	public String delete(@StringValidator(nullable = false) String id) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			ajr.setResMsg("删除成功!");
			if(StringUtils.isNotBlank(id)) {
				this.${baseInfo.entityName?uncapFirst}Service.deleteEntityById(id);
			} else {
				ajr.setResMsg("删除失败!");
				ajr.setResCode(302);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}
	
	/**
	 * 批量删除指定id的对象
	 * 
	 * @param ids
	 *            需要被删除的对象id组成的字符串
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "删除属性" , save = true)
	@Token(createToken = true , validateToken = true)
	@RequestMapping(value = "batchDelete" , method = RequestMethod.GET)
	public String batchDelete(@RegexpValidator(nullable = false , regexp = "^(\\w+,?)+\\w+$") String ids) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			ajr.setResMsg("删除成功!");
			if(StringUtils.isNotBlank(ids)) {
				boolean batchDelete = this.${baseInfo.entityName?uncapFirst}Service.batchDelete(ids.split(","));
				if(!batchDelete) {
					ajr.setResMsg("删除失败!");
					ajr.setResCode(302);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}
}
